# -*- coding: utf-8 -*-
import os
import sys
# add up one level dir into sys path
sys.path.append(os.path.abspath(os.path.dirname(
    os.path.dirname(os.path.dirname(__file__)))))
os.environ['DJANGO_SETTINGS_MODULE'] = 'webservices.settings'
import logging
from datetime import datetime
import requests
import json
from django.conf import settings
from common.mg_core.mg import MONGODB
from event_rule.dwc.qk_marketing_rule.daily_user_info import USER_INFO_REPORT
from common.es_core.report_creator import (
    ReportCreator,
    add_attachment_to_report_config
)
from preprocessor.dwc.model_router import ACCOUNT_MODEL_ROUTER
from event_rule.dwc.attachment.channel_tax_attachment import CHANNEL_TAX_ATTACHMENT

_LOGGER = logging.getLogger(__name__)


def create_qk_user_info(index):
    res = requests.get(url=settings.QK_CHANNEL_LIST_API)
    res_json = json.loads(res.content)
    chn_list = res_json['data']
    day_start_time = datetime(2019, 1, 1)
    day_end_time = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
    daily_report = ReportCreator.create_report(
        user_pool=None, start_time=day_start_time, end_time=day_end_time,
        event_rule=add_attachment_to_report_config(USER_INFO_REPORT, CHANNEL_TAX_ATTACHMENT),
        index=index,
        custom_filter=[{"bool": {"should": [{"terms": {"_chn": chn_list}}, {"terms": {"_qk_appid": chn_list}}]}}],
        custom_not_filter=[{"term": {"_user_id": 1}}], max_bucket=50000, to_group=True)
    user_pool = [user_info['_user_id'] for user_info in daily_report['list']]
    account_model = ACCOUNT_MODEL_ROUTER[index]
    users = account_model.objects.filter(**{'user_id__in': user_pool})
    user_map = {user.user_id: user for user in users}
    for report in daily_report['list']:
        if report['_user_id'] not in user_map:
            print(report['_user_id'], index)
            continue
        user_ins = user_map[report['_user_id']]
        to_update = {
            '$set': {
                'index': index,
                'user_id': int(report['_user_id']),
                'recharge': report['recharge'],
                'tax': report['tax'],
                'profit': report['profit'],
                'channel_tax': report['channel_tax_amount'],
                'real_channel_tax': report['real_channel_tax_amount'],
                'channel': user_ins.qk_appid if user_ins.qk_appid else user_ins.channel,
                'registered_ip': user_ins.ip,
                'last_active_at': datetime.fromtimestamp(report['last_active_at']),
                'last_active_ts': report['last_active_at'],
                'platform': 'ios' if user_ins.channel.startswith('ios') else 'android',
                'balance': report['account_info'].get('_source', {}).get('user_data_sync_balance', 0),
                'safe_balance': report['account_info'].get('_source', {}).get('user_data_sync_safe_balance', 0),
                'timestamp': day_end_time.timestamp() - 1,
                'registered_at': user_ins.registered_at
            },
            '$setOnInsert': {
                'total_recharge': 0,
                'total_profit': 0,
                'total_tax': 0,
                'total_real_channel_tax': 0
            }
        }
        record = MONGODB['qk']['market_user_info'].find_one({"_id": '-'.join([index, str(report['_user_id'])]),
                                                         "timestamp": {"$lt": day_start_time}})
        if record:
            MONGODB['qk']['market_user_info'].update_one(
                {"_id": '-'.join([index, str(report['_user_id'])]),
                 "timestamp": {"$lt": day_start_time}},
                {"$inc": {"total_recharge": record['recharge'],
                          "total_tax": record['tax'],
                          "total_profit": record.get('profit', 0),
                          "total_channel_tax_amount": record.get('channel_tax', 0),
                          "total_real_channel_tax": record.get(
                              'real_channel_tax', 0)}})
        MONGODB['qk']['market_user_info'].update_one({'_id': '-'.join([index, str(report['_user_id'])])}, to_update, True)


for index in settings.DWC_INDEX:
    create_qk_user_info(index)
